package com.example.demo.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.config.login.Userparam;
import com.example.demo.datasource.multi.dao.*;
import com.example.demo.datasource.multi.entity.Workflowentity;
import com.example.demo.datasource.multi.entity.applicationentity;
import com.example.demo.datasource.multi.entity.honorsentity;
import com.example.demo.datasource.multi.entity.user;
import com.example.demo.entity.detail.detail;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Controller
public class detailcontroller {

    @Autowired
    Applicationmapper applicationmapper;
    @Autowired
    com.example.demo.datasource.multi.dao.workflowmapper workflowmapper;
    @Autowired
    Honorsmapper honorsmapper;
    @Autowired
    com.example.demo.datasource.multi.dao.selectstringmapper selectstringmapper;
    @Autowired
    com.example.demo.datasource.multi.dao.usermapper usermapper;
    @Autowired
    com.example.demo.datasource.multi.dao.insertmapper insertmapper;




    @ResponseBody
    @RequestMapping("/getdetailbypkid")
    public JSON getdetailbypkid(@RequestBody Map<String,String> params, HttpServletRequest request){
        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        log.info("获取用户信息:"+user.getUsername());
        String sqlx="select * from user where username = '"+user.getUsername()+"'";

        com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sqlx);



        System.out.println(params.get("paramsp"));

        String sql1="select a.*,b.avatar,b.realname from application a left join userinfo b ON a.userid = b.userid where a.pkid = '"+params.get("paramsp")+"'";
        System.out.println(sql1);

        applicationentity applicationrel = applicationmapper.getapplication(sql1);
        System.out.println(applicationrel);

        SimpleDateFormat simpleDateFormat1 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间并作为时间戳
        String createtime=simpleDateFormat1.format(new Date());

        //打开详情进行状态变更判断
        if (applicationrel.getApprovalstatus().equals("2")&&theuser.getRolevalue().equals("Department")){
            if (applicationrel.getNumberofedits().equals("0")){
                String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("paramsp")+"'," +
                        "7," +
                        "6," +
                        "'3'" +
                        ",'"+applicationrel.getType()+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'初审审批中'" +
                        ",'true',0)";
                System.out.println(sql4);
                int result4= insertmapper.insert(sql4);
                System.out.println(result4);

                applicationrel.setApprovalstatus("3");
                applicationrel.setWorkflownumber("7");


            }else {
                String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("paramsp")+"'," +
                        "3," +
                        "2," +
                        "'3'" +
                        ",'"+applicationrel.getType()+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'初审审批中'" +
                        ",'true',0)";
                System.out.println(sql4);
                int result4= insertmapper.insert(sql4);
                System.out.println(result4);

                applicationrel.setApprovalstatus("3");
                applicationrel.setWorkflownumber("3");

            }

        }else if (applicationrel.getApprovalstatus().equals("4")&&theuser.getRolevalue().equals("Super")){
            if (applicationrel.getNumberofedits().equals("0")){
                String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("paramsp")+"'," +
                        "9," +
                        "8," +
                        "'5'" +
                        ",'"+applicationrel.getType()+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'终审审批中'" +
                        ",'true',0)";
                System.out.println(sql4);
                int result4= insertmapper.insert(sql4);
                System.out.println(result4);

                applicationrel.setApprovalstatus("5");
                applicationrel.setWorkflownumber("9");
            }else {
                String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("paramsp")+"'," +
                        "5," +
                        "4," +
                        "'5'" +
                        ",'"+applicationrel.getType()+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'终审审批中'" +
                        ",'true',0)";
                System.out.println(sql4);
                int result4= insertmapper.insert(sql4);
                System.out.println(result4);

                applicationrel.setApprovalstatus("5");
                applicationrel.setWorkflownumber("5");
            }


        }else if(applicationrel.getApprovalstatus().equals("0")&&theuser.getRolevalue().equals("student")){
            String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                    "VALUES(" +
                    "'"+params.get("paramsp")+"'," +
                    "5," +
                    "4," +
                    "'1'" +
                    ",'"+applicationrel.getType()+"'" +
                    ",'"+user.getUsername()+"'" +
                    ",'"+createtime+"'" +
                    ",'编辑'" +
                    ",'true',0)";
            System.out.println(sql4);
            int result4= insertmapper.insert(sql4);
            System.out.println(result4);

            applicationrel.setApprovalstatus("5");
            applicationrel.setWorkflownumber("5");
        }

        String sql2="select a.*,b.dictname from workflow a left join dict b on a.status = b.code  where a.pkid = '"+params.get("paramsp")+"' ORDER BY a.number";
        System.out.println(sql2);

        List<Workflowentity> wfrel= workflowmapper.getwf(sql2);
        System.out.println(wfrel);

        String sql3="select * from honors where pkid = '"+params.get("paramsp")+"'";
        System.out.println(sql3);

        List<honorsentity> hnrel = honorsmapper.gethonor(sql3);
        System.out.println(hnrel);
/*
        String sql4= "select username from user where id = "+applicationrel.getUserid();
        String username = selectstringmapper.selectstring(sql4);*/

        detail detailList = new detail();

        detailList.setId(applicationrel.getId());
        detailList.setCreater(applicationrel.getRealname());
        detailList.setPkid(applicationrel.getPkid());
        detailList.setApprovalstatus(applicationrel.getApprovalstatus());
        detailList.setCreatetime(applicationrel.getCreatetime());
        detailList.setStudentname(applicationrel.getStudentname());
        detailList.setStudentid(applicationrel.getStudentid());
        detailList.setContact(applicationrel.getContact());
        String sex=null;
        if (! (applicationrel.getSex() == null)){
            if (applicationrel.getSex().equals("1")){
                sex = "男";
            }else {
                sex = "女";
            }
        }

        detailList.setSex(sex);
        detailList.setNation(applicationrel.getNation());

        if (!(applicationrel.getPolitics() == null)){
            if (applicationrel.getPolitics().equals("1")){
                detailList.setPolitics("共青团员");
            }else if (applicationrel.getPolitics().equals("2")){
                detailList.setPolitics("党员");
            }else {
                detailList.setPolitics("群众");
            }


        }


        detailList.setCollege((applicationrel.getCollege()));
        detailList.setProfession(applicationrel.getProfession());
        detailList.setStudentclass(applicationrel.getStudentclass());

        if (applicationrel.getType().equals("individual")){
            detailList.setAveragescores(applicationrel.getAveragescores());
            detailList.setPost(applicationrel.getPost());
        }else {
            detailList.setStudentnumber(applicationrel.getStudentnumber());
            detailList.setDirector(applicationrel.getDirector());
        }

        detailList.setEvaluate(applicationrel.getEvaluate());
        detailList.setWorkflownumber(applicationrel.getWorkflownumber());
        detailList.setType(applicationrel.getType());
        detailList.setApplicationawards(applicationrel.getApplicationawards());
        detailList.setNumberofedits(applicationrel.getNumberofedits());
        /*
        * 学生：1、编辑中状态，status为1，返回一个编辑按钮，点击编辑跳转到编辑界面，2、其他状态不返回按钮
        *院级管理员：1、都返回两个按钮：批准、驳回
        * 校级管理员：1、返回批准、拒绝
        * */
        if (theuser.getRolevalue().equals("student")&&(applicationrel.getApprovalstatus().equals("1")||applicationrel.getApprovalstatus().equals("0"))){
            detailList.setEdit(true);
            detailList.setReject(false);
            detailList.setApprove(false);
            detailList.setRefuse(false);
            detailList.setNumberofedits(applicationrel.getNumberofedits());
        }else if (applicationrel.getApprovalstatus().equals("3")&&theuser.getRolevalue().equals("Department")){
            detailList.setEdit(false);
            detailList.setApprove(true);
            detailList.setRefuse(false);
            if (applicationrel.getNumberofedits().equals("1")){
                detailList.setReject(true);
            }else {
                detailList.setReject(false);
                detailList.setRefuse(true);
            }

        }else if (applicationrel.getApprovalstatus().equals("5")&&theuser.getRolevalue().equals("Super")){
            detailList.setEdit(false);
            detailList.setReject(false);
            detailList.setApprove(true);
            detailList.setRefuse(true);
        }else {
            detailList.setEdit(false);
            detailList.setReject(false);
            detailList.setApprove(false);
            detailList.setRefuse(false);
        }
        detailList.setAvatar(applicationrel.getAvatar());
        detailList.setPercent(wfrel.size()*(100/6));

        for (Workflowentity wff:wfrel
        ) {
            String dictname = wff.getDictname();
            wff.setStatus(dictname);
        }
        detailList.setWorkflowlist(wfrel);
        detailList.setHonorslist(hnrel);


        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",detailList);
        result5.put("message","获取成功!");
        result5.put("type","success");
        System.out.println("获取成功！");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;

    }

    @Autowired
    com.example.demo.datasource.multi.dao.updatemapper updatemapper;

    @ResponseBody
    @RequestMapping("/setaction")
    public JSON setaction(@RequestBody Map<String,String> params, HttpServletRequest request){
        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        log.info("获取用户信息:"+user.getUsername());
        SimpleDateFormat simpleDateFormat1 =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间并作为时间戳
        String createtime=simpleDateFormat1.format(new Date());

        System.out.println(params);
        System.out.println(params.get("param"));
        System.out.println(params.get("action"));
        System.out.println(params.get("status"));
        System.out.println(params.get("type"));
        System.out.println(params.get("workflownumber"));
        System.out.println(params.get("numberofedits"));

        String number = params.get("workflownumber");
        int previousnumberdel = Integer.parseInt(number)-1;
        int numberadd = Integer.parseInt(number)+1;

        if (params.get("action").equals("reject")){//驳回
            String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                    "VALUES(" +
                    "'"+params.get("param")+"'," +
                    ""+numberadd+"," +
                    ""+number+"," +
                    "'0'" +
                    ",'"+params.get("type")+"'" +
                    ",'"+user.getUsername()+"'" +
                    ",'"+createtime+"'" +
                    ",'初审驳回'" +
                    ",'true',0)";
            System.out.println(sql4);
            int result4= insertmapper.insert(sql4);
            System.out.println(result4);
            String sql2="update awards.application SET numberofedits = 0 WHERE pkid = '"+params.get("param")+"' ";  //修改驳回后可编辑次数
            int updaterel=updatemapper.update(sql2);
            System.out.println(updaterel);

        }else if (params.get("action").equals("approve")){
            String sqlx="select * from user where username = '"+user.getUsername()+"'";
            com.example.demo.datasource.multi.entity.user theuser=usermapper.getuser(sqlx);
            String sql4=null;
            if (theuser.getRolevalue().equals("Super")){
                 sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("param")+"'," +
                        ""+numberadd+"," +
                        ""+number+"," +
                        "'6'" +
                        ",'"+params.get("type")+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'终审通过'" +
                        ",'true',0)";

            }else {
                sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                        "VALUES(" +
                        "'"+params.get("param")+"'," +
                        ""+numberadd+"," +
                        ""+number+"," +
                        "'4'" +
                        ",'"+params.get("type")+"'" +
                        ",'"+user.getUsername()+"'" +
                        ",'"+createtime+"'" +
                        ",'初审通过'" +
                        ",'true',0)";

            }

            System.out.println(sql4);
            int result4= insertmapper.insert(sql4);
            System.out.println(result4);

        }else if (params.get("action").equals("refuse")){ //拒绝
            String sql4 = "insert into workflow(pkid,number,previousnumber,`status`,type,HANDLER,handletime,handleaction,isread,dr) " +
                    "VALUES(" +
                    "'"+params.get("param")+"'," +
                    ""+numberadd+"," +
                    ""+number+"," +
                    "'7'" +
                    ",'"+params.get("type")+"'" +
                    ",'"+user.getUsername()+"'" +
                    ",'"+createtime+"'" +
                    ",'终审不通过'" +
                    ",'true',0)";
            System.out.println(sql4);
            int result4= insertmapper.insert(sql4);
            System.out.println(result4);

        }

        Map<String,String> param = new HashMap<>();
        param.put("paramsp",params.get("param"));
        JSON result8 = getdetailbypkid(param,request);

        return result8;
    }
}
